package com.leha.core.services.imp;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.leha.core.dao.LhUserMapper;
import com.leha.core.entity.mybatis.LhUser;
import com.leha.core.entity.mybatis.LhUserExample;
import com.leha.core.services.ErrorMessageServices;
import com.leha.core.services.GameServices;
import com.leha.core.services.IUserServices;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.leha.core.constants.CoreErrorDict.GAME_NOT_EXIST;

@Service
public class IUserServicesImpl implements IUserServices {

    @Autowired
    private GameServices gameServices;
    @Autowired
    private LhUserMapper userMapper;
    @Autowired
    private ErrorMessageServices errorMessageServices;

    private static final Logger LOG = LoggerFactory.getLogger(IUserServicesImpl.class);

    @Override
    public LhUser login(Integer gameId, String code, String encryptedData, String iv) {
        try {
            WxMaService wxService = gameServices.getGameServices(gameId);
            if(wxService==null) {
                errorMessageServices.setError(GAME_NOT_EXIST);
                return null;
            }
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            LOG.info(session.getSessionKey());
            LOG.info(session.getOpenid());
            LhUserExample ex = new LhUserExample();
            ex.createCriteria().andOpenidEqualTo(session.getOpenid());
            List<LhUser> user = userMapper.selectByExample(ex);
            if(user.size()==0) {
                WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(session.getSessionKey(), encryptedData, iv);
                LhUser newUser = new LhUser();
                newUser.setOpenid(session.getOpenid());
                newUser.setAvatarUrl(userInfo.getAvatarUrl());
                newUser.setNickname(userInfo.getNickName());
                newUser.setGameId(1);
                userMapper.insertSelective(newUser);
                return newUser;
            } else {
                return user.get(0);
            }
        } catch (WxErrorException e) {
            LOG.error(e.getMessage(), e);
            return null;
        }
    }
}
